Template Method
It defines the skeleton of an algorithm in a base class, allowing subclasses to override specific steps of the algorithm without changing its overall structure. This pattern is useful when you have a common algorithm that can be implemented in different ways by subclasses.
Structure
- Abstract Class: Contains the template method that defines the algorithm's structure and may include some abstract methods that subclasses must implement.
- Concrete Classes: Subclasses that implement the abstract methods defined in the base class, providing specific behavior for those steps.
Example
// Template Interface
interface Meal {
// Template method
default void prepareMeal() {
gatherIngredients(); // Step 1: Gather ingredients
cook(); // Step 2: Cooking
serve(); // Step 3: Serving
}
// Method signatures for specific steps
void gatherIngredients();
void cook();
// Default method for serving the meal
default void serve() {
System.out.println("Serving the meal.");
}
}
// Concrete Class for preparing a Pasta dish
class Pasta implements Meal {
@Override
public void gatherIngredients() {
System.out.println("Gathering ingredients for Pasta: pasta, tomato sauce, cheese.");
}
@Override
public void cook() {
System.out.println("Cooking Pasta: boiling pasta and adding sauce.");
}
}
// Concrete Class for preparing a Salad dish
class Salad implements Meal {
@Override
public void gatherIngredients() {
System.out.println("Gathering ingredients for Salad: lettuce, tomatoes, cucumber, dressing.");
}
@Override
public void cook() {
System.out.println("Tossing the Salad ingredients together.");
}
}
// Client code
public class Main {
public static void main(String[] args) {
Meal pasta = new Pasta();
pasta.prepareMeal(); // Prepare Pasta
System.out.println(); // New line for separation
Meal salad = new Salad();
salad.prepareMeal(); // Prepare Salad
}
}